'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

let str = '';

class UserController extends Controller {
    //注册
    async registry() {
        let {ctx,service} = this;
        try{
            ctx.validate({username:'string',password:'string'});
            //查询此人是否存在
            let {username,password,role_name='普通用户',role_id='2'} = ctx.request.body;
            let target = await service.user.selectUser(username);
            if(target.length){
                ctx.body = {
                    code:4,
                    msg:'用户已存在'
                }
            }else{
                //22.注册
                try{
                    await service.user.registry(username,password,role_name,role_id);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body  = {
                        code:0,
                        msg:'注册失败'
                    }
                }
            }
        }catch(e){
            ctx.body = {
                code:2,
                msg:e
            }
        }
    }
    //登录
    async login(){
        let {ctx,service} = this;
        try{
            console.log(ctx.request.params);
            ctx.validate({username:'string',password:'string',code:'string'})

            let {username,password,code} = ctx.request.body;
            if(code != str){
                ctx.body = {
                    code:7,
                    msg:'验证码有误'
                }
                return false
            }
            let target = await service.user.login(username,password);
            if(target.length){
                let token = jwt.sign({username,user_id:target[0].id},'lixd',{expiresIn:60*60*5});

                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token,
                    role_name:target[0].role_name
                }
            }else{
                ctx.body = {
                    code:1,
                    msg:'登录成功'
                }
            }
        }catch(e){
            ctx.body = {
                code:2,
                msg:e
            }
        }
    }
    //获取验证码
    async code(){
        let {ctx,service} = this;

        str = '';

        for(let i = 0;i<4;i++){
            str += Math.floor(Math.random()*10)
        }
        ctx.body = {
            code:1,
            data:str
        }
    }
}

module.exports = UserController;
